use std::{rc::Rc, cell::RefCell, ops::Deref};

use crate::{function::{ render::render_system::AliceRender, command::canvas2d::Canvas2dCommand}};

#[derive(Clone)]
pub struct AliceSwap(Rc<RefCell<AliceSwapImpl>>);

impl Deref for AliceSwap {
    type Target = Rc<RefCell<AliceSwapImpl>>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}


impl AliceSwap {
    pub fn new() -> Self {
        Self(Rc::new(RefCell::new(AliceSwapImpl::default())))
    }

    pub fn canvas_command(&mut self , cmd:Canvas2dCommand) {
        self.borrow_mut().canvas_swap.submit_command(cmd)
    }

    pub fn submit_canvas_to_render(&self, render:&mut AliceRender) {
        self.borrow_mut().canvas_swap.submit_canvas_draw_command(render)
    }
  
}




#[derive(Default)]
pub struct AliceSwapImpl {
    pub(super) canvas_swap:CanvasSwapLayer
}

#[derive(Default)]
pub struct CanvasSwapLayer {
    pub canvas_commands:Vec<Canvas2dCommand>
}


impl CanvasSwapLayer {
    pub fn submit_command(&mut self , draw_command:Canvas2dCommand) {
        self.canvas_commands.push(draw_command)
    }

    pub fn submit_canvas_draw_command(&mut self, render:&mut AliceRender) {
        let commands = self.canvas_commands.drain(..).collect::<Vec<Canvas2dCommand>>();
        render.submit_canvas_draw_command(commands)
    }

}
